<template>
  <div class="personal-info-page">
    <div class="page-overlay">
      <div class="page-header">
        <a-button type="text" @click="goBack" class="back-btn">
          <template #icon>
            <ArrowLeftOutlined />
          </template>
          返回
        </a-button>
        <h1>个人资料</h1>

      </div>

      <div class="content-container">
      <a-form
        ref="formRef"
        :model="formState"
        :label-col="{ span: 4 }"
        :wrapper-col="{ span: 16 }"
        @finish="onFinish"
        @finishFailed="onFinishFailed"
        class="profile-form"
      >
        <!-- 头像上传 -->
        <!-- 头像上传区域修改 -->
        <a-form-item label="头像">
          <div class="avatar-upload-section">
            <a-avatar :size="80" :src="formState.userAvatar" class="current-avatar">
              {{ formState.userName?.charAt(0) || 'U' }}
            </a-avatar>
            <div class="upload-options">
              <a-upload
                :before-upload="beforeUpload"
                :show-upload-list="false"
                :custom-request="customUpload"
                accept="image/*"
              >
                <a-button type="primary" ghost :loading="uploading">
                  <template #icon>
                    <UploadOutlined />
                  </template>
                  {{ uploading ? '上传中...' : '上传头像' }}
                </a-button>
              </a-upload>
              <a-button type="link" @click="showUrlInput = !showUrlInput"> 网络链接 </a-button>
            </div>
          </div>
          <div v-if="showUrlInput" class="url-input-section">
            <a-input
              v-model:value="avatarUrl"
              placeholder="请输入头像网络链接"
              @blur="handleAvatarUrlChange"
              class="avatar-url-input"
            />
            <a-button type="primary" @click="handleAvatarUrlChange" size="small"> 确认 </a-button>
          </div>
        </a-form-item>

        <!-- 用户名 -->
        <a-form-item
          label="昵称"
          name="userName"
          :rules="[
            { required: true, message: '请输入昵称!' },
            { min: 1, message: '昵称至少1个字符' },
            { max: 20, message: '昵称最多20个字符' },
          ]"
        >
          <a-input v-model:value="formState.userName" placeholder="请输入昵称" />
        </a-form-item>

        <!-- 账号 -->
        <a-form-item
          label="账号"
          name="userAccount"
          :rules="[
            { required: true, message: '请输入账号!' },
            { min: 4, message: '账号至少4个字符' },
            { max: 20, message: '账号最多20个字符' },
            { pattern: /^[a-zA-Z0-9_]+$/, message: '账号只能包含字母、数字和下划线' },
          ]"
        >
          <a-input v-model:value="formState.userAccount" placeholder="请输入账号" />
        </a-form-item>

        <!-- 个人简介 -->
        <a-form-item
          label="个人简介"
          name="userProfile"
          :rules="[{ max: 200, message: '个人简介最多200个字符' }]"
        >
          <a-textarea
            v-model:value="formState.userProfile"
            placeholder="请输入个人简介"
            :rows="4"
            :maxlength="200"
            show-count
          />
        </a-form-item>

        <!-- 密码修改区域 -->
        <a-divider>密码修改</a-divider>

        <a-form-item label="修改密码">
          <a-switch
            v-model:checked="showPasswordChange"
            checked-children="开启"
            un-checked-children="关闭"
            @change="onPasswordChangeToggle"
          />
          <span style="margin-left: 8px; color: #666">开启后可以修改登录密码</span>
        </a-form-item>

        <template v-if="showPasswordChange">
          <!-- 新密码 -->
          <a-form-item
            label="新密码"
            name="userPassword"
            :rules="[
              { required: true, message: '请输入新密码!' },
              { min: 6, message: '密码至少6个字符' },
              { max: 20, message: '密码最多20个字符' },
            ]"
          >
            <a-input-password v-model:value="formState.userPassword" placeholder="请输入新密码" />
          </a-form-item>
        </template>

        <!-- 提交按钮 -->
        <a-form-item :wrapper-col="{ offset: 4, span: 16 }">
          <a-space>
            <a-button type="primary" html-type="submit" :loading="loading" :disabled="!canSubmit">
              保存修改
            </a-button>
            <a-button @click="resetForm"> 重置 </a-button>
          </a-space>
        </a-form-item>
      </a-form>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { message } from 'ant-design-vue'
import { useRouter } from 'vue-router'
import { ArrowLeftOutlined, UploadOutlined } from '@ant-design/icons-vue'
import { updateUser, getLoginUser, uploadAvatar } from '@/api/userController'
import { useLoginUserStore } from '@/stores/loginUser'

const router = useRouter()
const loginUserStore = useLoginUserStore()
const loading = ref(false)
const uploading = ref(false)
const showUrlInput = ref(false)
const avatarUrl = ref('')

const showPasswordChange = ref(false)
const formRef = ref()



// 表单数据
const formState = reactive<API.UserUpdateRequest>({
  id: undefined,
  userAccount: '',
  userName: '',
  userAvatar: '',
  userProfile: '',
  userPassword: '',
})

// 返回上一页
const goBack = () => {
  router.back()
}

// 检查是否可以提交表单
const canSubmit = computed(() => {
  // 基本字段验证
  if (!formState.userName || !formState.userAccount) {
    return false
  }

  // 如果没有开启密码修改，检查基本字段即可
  if (!showPasswordChange.value) {
    return true
  }

  // 如果开启了密码修改，需要检查密码是否有效
  const password = formState.userPassword

  // 密码不能为空
  if (!password || !password.trim()) {
    return false
  }

  // 密码长度检查
  if (password.length < 6 || password.length > 20) {
    return false
  }

  return true
})

// 密码修改开关切换
const onPasswordChangeToggle = (checked: boolean) => {
  if (!checked) {
    // 关闭密码修改时清空密码字段
    formState.userPassword = ''
    // 清除密码相关的验证错误
    if (formRef.value) {
      formRef.value.clearValidate(['userPassword'])
    }
  } else {
    // 开启密码修改时，如果已有密码值则重新验证
    if (formRef.value && formState.userPassword) {
      formRef.value.validateFields(['userPassword'])
    }
  }
}

// 加载用户信息
const loadUserInfo = async () => {
  try {
    const res = await getLoginUser()
    if (res.data.code === 0 && res.data.data) {
      const userData = res.data.data
      formState.id = userData.id
      formState.userAccount = userData.userAccount || ''
      formState.userName = userData.userName || ''
      formState.userAvatar = userData.userAvatar || ''
      formState.userProfile = userData.userProfile || ''
    } else {
      message.error('获取用户信息失败')
    }
  } catch (error) {
    console.error('获取用户信息失败：', error)
    message.error('获取用户信息失败')
  }
}

// 处理头像网络链接
const handleAvatarUrlChange = () => {
  if (avatarUrl.value.trim()) {
    formState.userAvatar = avatarUrl.value.trim()
    showUrlInput.value = false
    avatarUrl.value = ''
    message.success('头像链接已更新')
  }
}

// 文件上传前验证
const beforeUpload = (file: File) => {
  const isImage = file.type.startsWith('image/')
  if (!isImage) {
    message.error('只能上传图片文件!')
    return false
  }
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isLt2M) {
    message.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

// 自定义上传方法
const customUpload = async (options: any) => {
  const { file } = options
  uploading.value = true

  try {
    // 创建 FormData 对象
    const formData = new FormData()
    formData.append('file', file)

    // 调用 uploadAvatar 接口上传头像
    const result = await uploadAvatar(formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    })

    if (result.data.code === 0) {
      // 获取返回的头像 URL
      formState.userAvatar = result.data.data
      message.success('头像上传成功')
    } else {
      message.error('上传失败：' + result.data.message)
    }
  } catch (error) {
    console.error('上传失败：', error)
    message.error('上传失败，请重试')
  } finally {
    uploading.value = false
  }
}

// 提交表单
const onFinish = async (values: API.UserUpdateRequest) => {
  loading.value = true
  try {
    // 构建请求数据，如果没有修改密码则不传递password字段
    const updateData: API.UserUpdateRequest = {
      id: formState.id,
      userAccount: values.userAccount,
      userName: values.userName,
      userAvatar: formState.userAvatar,
      userProfile: values.userProfile,
    }

    // 只有当开启密码修改开关且输入了新密码时才包含password字段
    if (showPasswordChange.value && formState.userPassword && formState.userPassword.trim()) {
      updateData.userPassword = formState.userPassword
    }

    const res = await updateUser(updateData)

    if (res.data.code === 0) {
      message.success('个人资料更新成功')
      // 更新本地用户信息
      await loginUserStore.fetchLoginUser()
      // 可以选择返回上一页或刷新当前页面
      setTimeout(() => {
        goBack()
      }, 1000)
    } else {
      message.error('更新失败：' + res.data.message)
    }
  } catch (error) {
    console.error('更新个人资料失败：', error)
    message.error('更新失败，请重试')
  } finally {
    loading.value = false
  }
}

// 表单验证失败
const onFinishFailed = (errorInfo: { errorFields: Array<{ errors: string[] }> }) => {
  console.log('表单验证失败:', errorInfo)

  // 提取具体的错误信息
  const errors = errorInfo.errorFields
  if (errors && errors.length > 0) {
    const firstError = errors[0]
    if (firstError.errors && firstError.errors.length > 0) {
      message.error(firstError.errors[0])
      return
    }
  }

  message.error('请检查表单信息')
}

// 重置表单
const resetForm = () => {
  loadUserInfo()
  showUrlInput.value = false
  avatarUrl.value = ''
  showPasswordChange.value = false
  formState.userPassword = ''
}

// 页面加载时获取用户信息
onMounted(() => {
  loadUserInfo()
})
</script>

<style scoped>
.personal-info-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.page-overlay {
  min-height: 100vh;
  background: transparent;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.page-header {
  position: relative;
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(20px);
  padding: 20px 24px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.2);
  display: flex;
  align-items: center;
  gap: 16px;
  box-shadow: 0 2px 20px rgba(0, 0, 0, 0.1);
}

.back-btn {
  padding: 8px 16px;
  border-radius: 12px;
  background: rgba(255, 255, 255, 0.2);
  border: 1px solid rgba(255, 255, 255, 0.3);
  color: #ffffff;
  font-weight: 500;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  backdrop-filter: blur(10px);
}

.back-btn:hover {
  background: rgba(255, 255, 255, 0.3);
  border-color: rgba(255, 255, 255, 0.5);
  transform: translateY(-1px);
  box-shadow: 0 4px 16px rgba(102, 126, 234, 0.3);
  color: #ffffff;
}

.page-header h1 {
  margin: 0;
  font-size: 24px;
  font-weight: 700;
  color: #ffffff;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
  flex: 1;
}



.content-container {
  max-width: 900px;
  margin: 40px auto;
  background: rgba(255, 255, 255, 0.85);
  backdrop-filter: blur(20px);
  border-radius: 20px;
  padding: 40px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.15);
  border: 1px solid rgba(255, 255, 255, 0.4);
  transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
  animation: fadeInUp 0.6s ease-out;
}

.content-container:hover {
  transform: translateY(-4px) scale(1.01);
  box-shadow: 0 16px 48px rgba(102, 126, 234, 0.25);
  background: rgba(255, 255, 255, 0.9);
}

@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(30px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.profile-form {
  margin-top: 32px;
}

.profile-form :deep(.ant-form-item-label) {
  color: #333;
  font-weight: 600;
}

.profile-form :deep(.ant-input),
.profile-form :deep(.ant-input-password),
.profile-form :deep(.ant-input-password-input),
.profile-form :deep(.ant-input[type="password"]) {
  border-radius: 12px;
  border: 1px solid rgba(102, 126, 234, 0.25);
  background: rgba(255, 255, 255, 0.75);
  backdrop-filter: blur(15px);
  transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.profile-form :deep(.ant-input:hover),
.profile-form :deep(.ant-input-password:hover),
.profile-form :deep(.ant-input-password-input:hover) {
  border-color: #667eea;
  box-shadow: 0 4px 16px rgba(102, 126, 234, 0.2);
  background: rgba(255, 255, 255, 0.85);
  transform: translateY(-1px);
}

.profile-form :deep(.ant-input:focus),
.profile-form :deep(.ant-input-password:focus),
.profile-form :deep(.ant-input-password-input:focus) {
  border-color: #667eea;
  box-shadow: 0 6px 20px rgba(102, 126, 234, 0.3);
  background: rgba(255, 255, 255, 0.9);
  transform: translateY(-2px) scale(1.02);
}

.profile-form :deep(.ant-btn-primary) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  border-radius: 12px;
  font-weight: 500;
  box-shadow: 0 2px 8px rgba(102, 126, 234, 0.3);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.profile-form :deep(.ant-btn-primary:hover) {
  transform: translateY(-1px);
  box-shadow: 0 4px 16px rgba(102, 126, 234, 0.4);
  background: linear-gradient(135deg, #5a6fd8 0%, #6a4190 100%);
}

.profile-form :deep(.ant-btn-default) {
  border-radius: 12px;
  border: 1px solid rgba(102, 126, 234, 0.3);
  color: #667eea;
  background: rgba(255, 255, 255, 0.8);
  backdrop-filter: blur(10px);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.profile-form :deep(.ant-btn-default:hover) {
  background: rgba(102, 126, 234, 0.1);
  border-color: #667eea;
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(102, 126, 234, 0.2);
}

.avatar-upload-section {
  display: flex;
  align-items: center;
  gap: 20px;
  padding: 20px;
  background: rgba(102, 126, 234, 0.08);
  border-radius: 16px;
  border: 1px solid rgba(102, 126, 234, 0.15);
  backdrop-filter: blur(10px);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.avatar-upload-section:hover {
  background: rgba(102, 126, 234, 0.12);
  border-color: rgba(102, 126, 234, 0.25);
  transform: translateY(-1px);
  box-shadow: 0 4px 16px rgba(102, 126, 234, 0.1);
}

.current-avatar {
  border: 3px solid rgba(102, 126, 234, 0.3);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.current-avatar:hover {
  transform: scale(1.05);
  border-color: #667eea;
  box-shadow: 0 6px 20px rgba(102, 126, 234, 0.3);
}

.upload-options {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.url-input-section {
  margin-top: 16px;
  display: flex;
  gap: 12px;
  align-items: center;
  padding: 16px;
  background: rgba(255, 255, 255, 0.7);
  border-radius: 12px;
  border: 1px solid rgba(102, 126, 234, 0.2);
  backdrop-filter: blur(10px);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  animation: slideInDown 0.3s ease-out;
}

.url-input-section:hover {
  background: rgba(255, 255, 255, 0.85);
  border-color: rgba(102, 126, 234, 0.3);
  box-shadow: 0 2px 12px rgba(102, 126, 234, 0.15);
}

@keyframes slideInDown {
  from {
    opacity: 0;
    transform: translateY(-10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.avatar-url-input {
  flex: 1;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-header {
    padding: 16px 20px;
  }
  
  .page-header h1 {
    font-size: 20px;
  }
  
  .change-bg-hint {
    right: 20px;
    font-size: 11px;
    padding: 4px 12px;
  }
  
  .content-container {
    margin: 20px 16px;
    padding: 24px 20px;
    border-radius: 16px;
  }

  .profile-form :deep(.ant-form-item-label) {
    text-align: left;
  }

  .profile-form :deep(.ant-col-4) {
    flex: 0 0 100%;
    max-width: 100%;
  }

  .profile-form :deep(.ant-col-16) {
    flex: 0 0 100%;
    max-width: 100%;
  }

  .avatar-upload-section {
    flex-direction: column;
    align-items: center;
    gap: 16px;
    padding: 16px;
  }

  .upload-options {
    flex-direction: row;
    width: 100%;
    justify-content: center;
  }
  
  .url-input-section {
    padding: 12px;
    gap: 8px;
  }
}

/* 动画效果 */
@keyframes pulse {
  0% {
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.2);
  }
  50% {
    box-shadow: 0 12px 40px rgba(102, 126, 234, 0.3);
  }
  100% {
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.2);
  }
}

.personal-info-page:active .content-container {
  animation: pulse 0.3s ease-in-out;
}

/* 表单项动画 */
.profile-form :deep(.ant-form-item) {
  transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
  opacity: 0;
  animation: fadeInLeft 0.6s ease-out forwards;
}

.profile-form :deep(.ant-form-item:nth-child(1)) { animation-delay: 0.1s; }
.profile-form :deep(.ant-form-item:nth-child(2)) { animation-delay: 0.2s; }
.profile-form :deep(.ant-form-item:nth-child(3)) { animation-delay: 0.3s; }
.profile-form :deep(.ant-form-item:nth-child(4)) { animation-delay: 0.4s; }
.profile-form :deep(.ant-form-item:nth-child(5)) { animation-delay: 0.5s; }
.profile-form :deep(.ant-form-item:nth-child(6)) { animation-delay: 0.6s; }
.profile-form :deep(.ant-form-item:nth-child(7)) { animation-delay: 0.7s; }
.profile-form :deep(.ant-form-item:nth-child(8)) { animation-delay: 0.8s; }

.profile-form :deep(.ant-form-item:hover) {
  transform: translateX(6px) scale(1.01);
}

@keyframes fadeInLeft {
  from {
    opacity: 0;
    transform: translateX(-20px);
  }
  to {
    opacity: 1;
    transform: translateX(0);
  }
}

/* 分割线样式 */
.profile-form :deep(.ant-divider) {
  border-color: rgba(102, 126, 234, 0.25);
  margin: 32px 0;
  transition: all 0.3s ease;
}

.profile-form :deep(.ant-divider-inner-text) {
  color: #667eea;
  font-weight: 600;
  background: rgba(255, 255, 255, 0.8);
  padding: 8px 24px;
  border-radius: 16px;
  backdrop-filter: blur(10px);
  box-shadow: 0 2px 8px rgba(102, 126, 234, 0.1);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.profile-form :deep(.ant-divider:hover .ant-divider-inner-text) {
  background: rgba(255, 255, 255, 0.95);
  transform: scale(1.05);
  box-shadow: 0 4px 16px rgba(102, 126, 234, 0.2);
}

/* 开关样式 */
.profile-form :deep(.ant-switch) {
  background: rgba(102, 126, 234, 0.2);
}

.profile-form :deep(.ant-switch-checked) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

/* 文本域样式 */
.profile-form :deep(.ant-input) {
  resize: none;
}

.profile-form :deep(.ant-input::-webkit-scrollbar) {
  width: 6px;
}

.profile-form :deep(.ant-input::-webkit-scrollbar-track) {
  background: rgba(102, 126, 234, 0.1);
  border-radius: 3px;
}

.profile-form :deep(.ant-input::-webkit-scrollbar-thumb) {
  background: rgba(102, 126, 234, 0.3);
  border-radius: 3px;
  transition: background 0.3s ease;
}

.profile-form :deep(.ant-input::-webkit-scrollbar-thumb:hover) {
  background: rgba(102, 126, 234, 0.5);
}

/* 表单标签样式增强 */
.profile-form :deep(.ant-form-item-label > label) {
  color: #4a5568;
  font-weight: 600;
  transition: all 0.3s ease;
}

.profile-form :deep(.ant-form-item:hover .ant-form-item-label > label) {
  color: #667eea;
  transform: translateX(2px);
}
</style>
